package Process;

import LockService.LockService;
import LockService.LockMessage;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Date;
import java.util.Scanner;

public class ClientProcess {
    public static void main(String[] args) throws InterruptedException {
        ClassPathXmlApplicationContext clientContext = new ClassPathXmlApplicationContext("Client.xml");
        clientContext.start();
        LockService RPCLock = (LockService) clientContext.getBean("RPCLock");
        boolean RPCResult = RPCLock.test();
        System.out.println(RPCResult);

        int clientId = RPCLock.getClientId();
        System.out.println("myClientId is " + clientId);
        int clientApplyId = 0; //此客户端的申请id， 与clientId组合可唯一标识每一次申请

        LockMessage lockMessage = new LockMessage();
        lockMessage.setLockedMethod("testLock");
        lockMessage.setClientId(clientId);
        lockMessage.setClientApplyId(clientApplyId++);
        lockMessage.setAcquireTime(new Date());
        lockMessage.setTimeoutSeconds(10);
        lockMessage.setStatus("acquire");

        while(!RPCLock.acquireLock(lockMessage)){
            System.out.println("acquire locker failed……");
        }

        System.out.println("get the testLock succeed!");
        Thread.sleep(5000);

        Scanner scan = new Scanner(System.in);
        String uselessStr = scan.nextLine();

        lockMessage.setClientApplyId(clientApplyId++);
        if(RPCLock.releaseLock(lockMessage)){
            System.out.println("release the testLock succeed!");
        }
    }
}
